# -*- coding:utf-8 -*-
# time: 2025/5/23 ♡  09:23
# author:张伟
import random
import string
# Image：一个画布
# ImageDraw：画笔
# ImageFont：字体
from PIL import Image, ImageDraw, ImageFont


# 安装：pip install Pillow

# 图形验证码：
class Captcha(object):
    # 生成几位验证码
    number = 4
    # 验证码图片的宽高
    size = (100, 30)
    # 验证码字体大小
    font_size = 25
    # 干扰线条数
    line_number = 2

    # 构建验证码源文件:大小写字母和数字
    SOURCE = list(string.ascii_letters)
    for index in range(0, 10):
        SOURCE.append(str(index))

    # 生成随机颜色：R,G,B
    @classmethod
    def __gene_random_color(cls, start=0, end=255):
        # 初始化随机数种子
        random.seed()
        return random.randint(start, end), random.randint(start, end), random.randint(start, end)

    # 生成随机字体
    @classmethod
    def __gene_random_font(cls):
        fonts = [
            "ARIALNI.TTF",
            "BASKVILL.TTF",
            "COPRGTL.TTF",
            "lucon.ttf",
            "STKAITI.TTF"
        ]
        font = random.choice(fonts)
        return "utils/captcha/" + font

    # 生成验证码字符串
    @classmethod
    def __gene_text(cls):
        return "".join(random.sample(cls.SOURCE, cls.number))

    # 绘制干扰线
    @classmethod
    def __gene_line(cls, draw, width, height):
        begin = (random.randint(0, width), random.randint(0, height))
        end = (random.randint(0, width), random.randint(0, height))
        draw.line([begin, end], fill=cls.__gene_random_color(), width=2)

    # 绘制噪点
    @classmethod
    def __gene_points(cls, draw, point_chance, width, height):
        # 噪点的概率[0, 100]
        chance = min(100, max(0, int(point_chance)))
        for w in range(width):
            for h in range(height):
                tmp = random.randint(0, 100)
                if tmp > 100 - chance:
                    draw.point((w, h), fill=cls.__gene_random_color())




    # 生成验证码
    @classmethod
    def gene_graph_captcha(cls):
        # 验证码的宽高
        width, height = cls.size
        # 创建图片
        # R：Red（红色）0-255
        # G：G（绿色）0-255
        # B：B（蓝色）0-255
        # A：Alpha（透明度）
        image = Image.new("RGBA", (width, height), cls.__gene_random_color(0, 100))
        # 验证码字体
        font = ImageFont.truetype(cls.__gene_random_font(), cls.font_size)
        # 创建画笔
        draw = ImageDraw.Draw(image)
        # 生成字符串
        text = cls.__gene_text()
        # 获取字体的尺寸
        # 获取字体的边界框（左、上、右、下），用于后续文字位置计算
        text_bbox = font.getbbox(text)
        # 如果需要宽高，可以这样获取：
        font_width = text_bbox[2] - text_bbox[0]
        font_height = text_bbox[3] - text_bbox[1]
        # 填充字符串
        draw.text(((width-font_width)/2, (height-font_height)/2), text, font=font, fill=cls.__gene_random_color(150, 255))
        # 绘制干扰线
        for i in range(cls.line_number):
            cls.__gene_line(draw, width, height)
        # 绘制噪点
        cls.__gene_points(draw, 10, width, height)

        return image, text


